import flvjs from "flv.js";
import axios from "axios";

export class LivegbsFlvPlayer {
    constructor(axios,livegbsHost,channelID,deviceID,videoElementID) {
        this.axios = axios;
        this.livegbsHost = livegbsHost;
        this.channelID = channelID;
        this.deviceID = deviceID;
        this.videoElementID = videoElementID;
        this.flvPlayer = null;
        this.medieConconfig = null;

        this.getFlvUrl();
    }

    getFlvUrl() {
        if(this.livegbsHost) {
            axios.get(`/livegbs/api/v1/stream/start?serial=${this.channelID}&code=${this.deviceID}`).then((res) => {
                if (flvjs.isSupported()) {
                    let videoElement = document.getElementById(this.videoElementID);
                    if(!videoElement) {
                        return;
                    }
                    let flvUrl = res.data.FLV;
                    flvUrl = flvUrl.replace(this.livegbsHost,'/livegbs');
                    this.medieConconfig = {
                        type: 'flv',
                        isLive: true,
                        url:flvUrl,
                        hasAudio:true,
                        hasVideo:true,
                        enableStashBuffer: true
                    };
                    this.flvPlayer = flvjs.createPlayer(this.medieConconfig);
                    this.flvPlayer.attachMediaElement(videoElement);
                    this.flvPlayer.load();
                    this.flvPlayer.play();
                }
            });
        }else {
            let videoElement = document.getElementById(this.videoElementID);
            if(!videoElement) {
                return;
            }
            let flvUrl = this.deviceID;
            this.medieConconfig = {
                type: 'flv',
                isLive: true,
                url:flvUrl,
                hasAudio:true,
                hasVideo:true,
                enableStashBuffer: true
            };
            this.flvPlayer = flvjs.createPlayer(this.medieConconfig);
            this.flvPlayer.attachMediaElement(videoElement);
            this.flvPlayer.load();
            this.flvPlayer.play();
        }
    }

    destroy() {
        if(this.flvPlayer) {
            this.flvPlayer.unload();
            this.flvPlayer.detachMediaElement();
            this.flvPlayer.destroy();
        }
    }

    pause() {
        if(this.flvPlayer) {
            this.flvPlayer.pause();
        }
    }

    play() {
        if(this.flvPlayer) {
            this.flvPlayer.play();
        }
    }

    getFlvPlayer() {
        return this.flvPlayer;
    }

    getMediaConfig() {
        return this.medieConconfig;
    }

    getDeviceID() {
      return this.deviceID;
    }
}
